package cn.codesea.housework_user.ui;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.codesea.housework_user.R;
import cn.codesea.housework_user.entity.User;
import cn.codesea.housework_user.net.ServiceGenerator;
import cn.codesea.housework_user.net.data.Result;
import cn.codesea.housework_user.net.service.UserService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterOldActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;


    @BindView(R.id.pwd_et)
    EditText pwd_et;
    @BindView(R.id.name_et)
    EditText name_et;
    @BindView(R.id.sex_et)
    EditText sex_et;
    @BindView(R.id.cif_et)
    EditText cif_et;
    @BindView(R.id.phone_et)
    EditText phone_et;
    @BindView(R.id.birth_et)
    EditText birth_et;
    @BindView(R.id.address_et)
    EditText address_et;

    @BindView(R.id.submit_tv)
    AppCompatButton submit_tv;


    @BindView(R.id.height_et)
    EditText height_et;
    @BindView(R.id.weight_et)
    EditText weight_et;
    @BindView(R.id.work_state_et)
    EditText work_state_et;
    @BindView(R.id.thinking_ability_et)
    EditText thinking_ability_et;
    @BindView(R.id.selfcare_ability_et)
    EditText selfcare_ability_et;
    @BindView(R.id.expression_ability_et)
    EditText expression_ability_et;

    User older;
    String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_old);
        ButterKnife.bind(this);
        init();
    }

    private void init(){
        initData();
        initView();
    }

    private void initData(){
        Intent data = getIntent();
        type = data.getStringExtra("type");
        if ("update".equals(type)){
            // 修改信息
            older = (User)data.getSerializableExtra("older");
        }
    }

    public void initToolbar(){
        // 初始化 toolbar
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(RegisterOldActivity.this,MainActivity.class));
                finish();
            }
        });
    }

    public void initView(){
        initToolbar();

        if(older != null){
            pwd_et.setText(older.getPwd());
            name_et.setText(older.getName());
            sex_et.setText(older.getSex());
            cif_et.setText(older.getCif_no());
            phone_et.setText(older.getPhone());
            birth_et.setText(older.getBirth());
            address_et.setText(older.getAdress());

            height_et.setText(older.getHeight());
            weight_et.setText(older.getWeight());
            work_state_et.setText(older.getWork_state());
            thinking_ability_et.setText(older.getThinking_ability());
            selfcare_ability_et.setText(older.getSelfcare_ability());
            expression_ability_et.setText(older.getExpression_ability());
        }

    }

    @OnClick({R.id.sex_et})
    public void sex_et(){
        final String[] Items = new String[] {"男","女"};
        showDialog(sex_et,Items);
    }

    @OnClick({R.id.birth_et})
    public void birth_et(){
        showDialog_birth(birth_et);
    }

    @OnClick(R.id.submit_tv)
    public void submit_tv(){
        User user = new User();

        if("child".equals(type)){// 子女页面过来的
            user.setPid(getIntent().getIntExtra("userid",-1));
        }

        user.setType(1);// 老人注册
        user.setPwd(pwd_et.getText().toString());
        user.setName(name_et.getText().toString());
        user.setSex(sex_et.getText().toString());
        user.setCif_no(cif_et.getText().toString());
        user.setPhone(phone_et.getText().toString());
        user.setAdress(address_et.getText().toString());
        user.setBirth(birth_et.getText().toString());

        user.setHeight(height_et.getText().toString());
        user.setWeight(weight_et.getText().toString());
        user.setWork_state(work_state_et.getText().toString());
        user.setExpression_ability(expression_ability_et.getText().toString());
        user.setSelfcare_ability(selfcare_ability_et.getText().toString());
        user.setThinking_ability(thinking_ability_et.getText().toString());

        UserService service = ServiceGenerator.createService(UserService.class);

        if (this.older == null) {// 注册流程
            // 网络请求
            Call<Result> call = service.userRegister(user);
            call.enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    StringBuffer msg = new StringBuffer();
                    if("child".equals(type)) {// 子女新增
                        msg.append("新增");
                    }else{
                        msg.append("注册");
                    }
                    resultProcess(response.body(),msg.toString());
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(RegisterOldActivity.this,"网络错误!",Toast.LENGTH_SHORT).show();
                }
            });
        }else {// 修改流程

            user.setUserid(older.getUserid());
            user.setPid(older.getPid());

            Call<Result> call = service.userUpdate(user);
            call.enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    resultProcess(response.body(),"修改");
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(RegisterOldActivity.this,"网络错误!",Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    /**
     * 结果处理
     */
    public void resultProcess(Result result,String msg){
        if (result.getState() == 200){
            Dialog dialog = new AlertDialog.Builder(RegisterOldActivity.this)
                    .setTitle("提示")
                    .setMessage(msg + "成功！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
//                            startActivity(new Intent(RegisterOldActivity.this,LoginActivity.class));
                            finish();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();
        }else {
            Dialog dialog = new AlertDialog.Builder(RegisterOldActivity.this)
                    .setTitle("提示")
                    .setMessage(msg + "失败！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();
        }
    }

    @OnClick(R.id.work_state_et)
    public void work_state_et(){
        final String[] Items = new String[] {"退休","在职"};
        showDialog(work_state_et,Items);
    }

    @OnClick(R.id.thinking_ability_et)
    public void thinking_ability_et(){
        final String[] Items = new String[] {"正常","迷糊","痴呆"};
        showDialog(thinking_ability_et,Items);
    }

    @OnClick(R.id.selfcare_ability_et)
    public void selfcare_ability_et(){
        final String[] Items = new String[] {"正常","无"};
        showDialog(selfcare_ability_et,Items);
    }

    @OnClick({R.id.expression_ability_et})
    public void expression_ability_et(){
        final String[] Items = new String[] {"正常","无"};
        showDialog(expression_ability_et,Items);
    }

    /**
     * 日期选择
     * @param et
     */
    public void showDialog_birth(final EditText et){
        new DatePickerDialog(RegisterOldActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {
                        monthOfYear += 1;
                        et.setText(year+"-"+monthOfYear+"-"+dayOfMonth);
                    }
                }, Calendar.getInstance().get(Calendar.YEAR), Calendar
                .getInstance().get(Calendar.MONTH), Calendar
                .getInstance().get(Calendar.DATE)).show();
    }


    /**
     * 通用选择框
     * @param et
     * @param Items
     */
    public void showDialog(final EditText et,final String[] Items){
        Dialog allertDialog = new AlertDialog.Builder(RegisterOldActivity.this).setItems(Items,new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                et.setText(Items[which]);
            }
        } ).create();
        allertDialog.show();
    }

}
